<template>
  <div class="app-container">
    <el-form :inline="true">

      <el-form-item>
        <el-date-picker
          v-model="seDate"
          size="mini"
          type="daterange"
          range-separator="至"
          start-placeholder="请验时间(起始)"
          end-placeholder="请验时间(结束)">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
          <el-select v-model="queryParam.checkTypeName" placeholder="请选择品类" size="mini" clearable>
            <el-option
              v-for="item in options"
              :key="item.productCategoryName"
              :label="item.productCategoryName"
              :value="item.productCategoryName">
            </el-option>
          </el-select>
      </el-form-item>

      <el-form-item>
          <el-input placeholder="品名" v-model="queryParam.productName" :clearable="true" size="mini"/>
      </el-form-item>

      <el-form-item>
          <el-input placeholder="GMP编码" v-model="queryParam.productGmp" :clearable="true" size="mini"/>
      </el-form-item>

      <el-form-item>
          <el-input placeholder="批号" v-model="queryParam.batchNum" :clearable="true" size="mini"/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" class="pan-btn primary-btn" icon="el-icon-search" size="mini" @click="getData()">搜索</el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="warning" class="pan-btn warning-btn" icon="el-icon-edit" size="mini" @click="checkTimeManagerVisible = true;queryCycles()">周期管理</el-button>
      </el-form-item>

      <el-form-item>
        <el-button size="mini" :loading="downloadingStatus" @click="downData()">导出</el-button>
      </el-form-item>


    </el-form>

      <el-table
	    id="out-table"
        v-loading = "isLoading"
        element-loading-background = "rgba(255, 255, 255, .5)"
        element-loading-text = "加载中，请稍后..."
        element-loading-spinner = "el-icon-loading"
        :data="tableData"
        style="width: 100%"
        :row-class-name="tableRowClassName"
        >
        <el-table-column
              type="index"
              width="50">
        </el-table-column>
        <el-table-column
          prop="checkId"
          label="编号">
        </el-table-column>
        <el-table-column
          prop="productGmp"
          label="GMP编码">
        </el-table-column>
        <el-table-column
          prop="productSpec"
          label="GMP编码">
				<template slot-scope="{row}">
					<span v-html="row.productSpec"></span>
				</template>
        </el-table-column>
        <el-table-column
          prop="checkTypeName"
          label="品类">
        </el-table-column>
        <el-table-column
          prop="productName"
          label="品名">
        </el-table-column>
        <el-table-column
          prop="batchNum"
          label="批号">
        </el-table-column>
        <el-table-column
          width="240px"
          prop="dispenseDate"
          label="分样时间">
        </el-table-column>
        <el-table-column
          width="240px"
          prop="dueReportDate"
          label="应出报告时间">
        </el-table-column>
        <el-table-column
          label="超时检验组"
          >
          <template slot-scope="{row}">
           <span v-for="(group,key) in row.unFinishGroup" :key="key">
              <el-badge :value="group.length" style="margin-top: 10px;">
                <el-popover
                    placement="top-start"
                    :title="key+'未完成检验项'"
                    width="260"
                    trigger="hover"
                    :content="group">
                    <el-button size="mini" slot="reference">{{key}}</el-button>
                  </el-popover>
              </el-badge>
              &nbsp;
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="usedDay"
          label="已用天数">
        </el-table-column>
        <el-table-column
          prop="standCheckDay"
          label="常规检验天数">
        </el-table-column>
        <el-table-column
          label="超期天数">
           <template slot-scope="{row}">
             <span style="color: red;">{{row.overDueDay}}</span>
           </template>
        </el-table-column>
      </el-table>

<!--    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="queryParam.pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="queryParam.pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination> -->

    <el-dialog
      title="检验周期调整"
      :visible.sync="checkTimeManagerVisible"
      width="60%"
      center>
      <span>

        <el-form :inline="true">
          <el-form-item label="品类:">
              <el-select style="width: 100px;" v-model="cycle.checkType" placeholder="请选择" size="mini" clearable>
              <el-option
                v-for="item in options"
                :key="item.productCategoryName"
                :label="item.productCategoryName"
                :value="item.productCategoryName">
              </el-option>
              </el-select>
          </el-form-item>

          <el-form-item label="检验组:">
              <el-select style="width: 100px;" v-model="cycle.groupName" placeholder="请选择" size="mini" clearable>
              <el-option
                v-for="item in groups"
                :key="item.inspectionGroupName"
                :label="item.inspectionGroupName"
                :value="item.inspectionGroupName">
              </el-option>
              </el-select>
          </el-form-item>

          <el-form-item label="检验项:">
              <el-input v-model="cycle.itemName" size="mini" style="width: 100px;"/>
          </el-form-item>

          <el-form-item label="标准检验周期:">
              <el-input type="number" v-model="cycle.day" :min="1" size="mini" style="width: 100px;"/>
          </el-form-item>

          <el-form-item>
              <el-button size="mini" type="success" class="pan-btn success-btn" @click="createCycle">保存</el-button>
          </el-form-item>

          <el-form-item>
              <el-button size="mini" type="primary" class="pan-btn primary-btn" icon="el-icon-search" @click="queryCycles()">搜索</el-button>
          </el-form-item>

          <el-form-item>
              <el-button size="mini" type="info" class="pan-btn info-btn" icon="el-icon-refresh" @click="restQuery">重置</el-button>
          </el-form-item>

        </el-form>

        <el-row style="margin-top: 10px;" :gutter="12" v-for="(vo, index) in cyclesVo" :key="index">
          <el-col :span="8" v-for="(cycle, index) in vo" :key="index">
            <el-card shadow="always">
              <div slot="header" class="clearfix">
                <h1>{{cycle.day}}天</h1>
                <div style="float: right;" type="text">
                  <el-popconfirm
                    title="这是一个现行检验周期规则确定删除吗？"
                    @confirm="delCycle(cycle)">
                    <el-button slot="reference" size="mini" type="warning" icon="el-icon-delete" />
                  </el-popconfirm>
                </div>
              </div>
              <div class="text item">
               <h4>品类：{{cycle.checkType}}</h4>
              </div>
              <div class="text item">
               <h4>
                  检验组：{{cycle.groupName}}
               </h4>
              </div>
              <div class="text item">
               <h4>
                  检验项：{{cycle.itemName}}
               </h4>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </span>
    </el-dialog>

</div>
</template>
<script>

  import { mapGetters } from 'vuex'
  import { queryCheckDelay,cycle,cycles,delCycle,visit } from '@/api/tables'
  import { CODE_OK } from '@/common/js/config'
  import { isBlank,dateCompare,parseTime } from '@/common/js/utils'
  import { isNumber } from '@/common/js/validate'
  import { getProductCategorys } from "@/api/product"
  import { getGroupList } from "@/api/inspection"
  export default{
    name: 'checkDelay',
    data() {
      return{
        isLoading:false,
        cycle:{
          checkType:"",
          groupName:"",
          itemName:"",
          day:1
        },
        options: [],
        groups:[],
        checkTimeManagerVisible:false,
        queryParam:{
          checkTypeName:"成品",
          productName:"",
          productGmp:"",
          batchNum:"",
          startTime:"",
          endTime:""
        },
        seDate:["2023-01-01","2023-12-31"],
        totalPage:1,
        tableData: [],
        cyclesVo:[],
		downloadingStatus:false
      }
    },
    computed: {},
    mounted() {
	  visit("检验超期查询").then().catch()
      this.getData()
      //品类
      getProductCategorys().then(res => {
      	if (res.code === CODE_OK) {
      		this.options = res.categorys
      	}
      })
      const params = {
      	page: 0,
        limit: 20,
      	groupName: null
      }
      getGroupList(params).then(res=>{
        if (res.code === CODE_OK) {
            this.groups = res.page.list
        }
      }).catch()
    },
    methods: {
      delCycle(cycle){
        delCycle(cycle.id).then(res=>{
          if (res.code === CODE_OK) {
            this.$message.success("删除成功")
            this.queryCycles()
          }else{
            this.$message.error(res.msg)
          }
        }).catch();
      },
      restQuery(){
        this.cycle = this.$options.data.call(this).cycle
      },
      queryCycles(){
        cycles(this.cycle).then(res=>{
          if (res.code === CODE_OK) {
            this.cyclesVo = this.arrTrans(3,res.data)
          }else{
            this.$message.error(res.msg)
          }
        }).catch()
      },
      createCycle(){
        //this.cycle = this.$options.data().cycle
        cycle(this.cycle).then(res=>{
          if (res.code === CODE_OK) {
            this.$message.success("创建成功")
            this.queryCycles()
          }else{
            this.$message.error(res.msg)
          }
        }).catch();
      },
      arrTrans(num, arr){
        // 一维数组转换为二维数组
          const iconsArr = []; // 声明数组
          arr.forEach((item, index) => {
            const page = Math.floor(index / num); // 计算该元素为第几个素组内
            if (!iconsArr[page]) { // 判断是否存在
              iconsArr[page] = [];
            }
            iconsArr[page].push(item);
          });
          return iconsArr;
      },
      getData(){
        this.isLoading = true;
        if(this.seDate.length == 2){
          this.queryParam.startTime = this.seDate[0]
          this.queryParam.endTime = this.seDate[1]
        }
        queryCheckDelay(this.queryParam).then(res=>{
          if (res.code === CODE_OK) {
            this.tableData = res.data
            this.isLoading = false;
          }
        }).catch();
      },
	  downData(){
		this.exportData();
	  },

	      //导出功能
	      exportData(){
	        let excelName = '检验超期.xlsx';
	        var xlsxParam = { raw: true };//转换成excel时，使用原始的格式
	        // 克隆节点
	        let tables = document.getElementById("out-table").cloneNode(true);
	        // 判断是否为固定列，解决（为固定列时，会重复生成表格）
	        if (tables.querySelector('.el-table__fixed') !== null) {
	          tables.removeChild(tables.querySelector('.el-table__fixed'))
	        }
	        let table_book = this.$XLSX.utils.table_to_book(tables,xlsxParam);
	        var table_write = this.$XLSX.write(table_book, {
	            bookType: "xlsx",
	            bookSST: true,
	            type: "array"
	        });
	        try {
	            this.$FileSaver.saveAs(
	                new Blob([table_write], { type: "application/octet-stream" }),
	                excelName
	            );
	        } catch (e) {
	            if (typeof console !== "undefined") console.log(e, table_write);
	        }
	        return table_write;
			},
      sizeChangeHandle(){},
      currentChangeHandle(){},
      tableRowClassName({row, rowIndex}) {
        if (rowIndex === 1) {
          return 'warning-row';
        } else if (rowIndex === 3) {
          return 'success-row';
        }
        return '';
      }
    }
  }
</script>

<style>

    .el-form-item__content {
      line-height: normal;
    }

    .el-table .warning-row {
     /* background: oldlace; */
    }

    .el-table .success-row {
      /* background: #f0f9eb; */
    }

</style>
